package redisson.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class LockController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/lock")
    public String demo(){
        RLock lock = null;
        boolean locked = false;
        try{
            log.info("开始执行demo方法");
            // 先获取分布式锁
            lock = redissonClient.getLock("demo-lock");
            locked = lock.tryLock(0, 5, TimeUnit.SECONDS);
            if(locked){
                //加锁成功， 执行业务逻辑
                log.info("业务执行开始。。。。");
                try {Thread.sleep(3000);} catch (Exception e) {throw new RuntimeException(e);}
                log.info("业务执行完成！！！");
            }else{
                //加锁失败
                log.info("获取分布式锁失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放分布式锁
            if(locked && lock != null){
                lock.unlock();
                log.info("释放分布式锁失败");
            }
        }
        return "ok";
    }
}